#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>

using namespace SocketModule;
using namespace LogModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &sock, InetAddr &client)>;

// 主要解决：连接的问题，IO通信的问题
// 细节: TcpServer,需不需要关心自己未来传递的信息是什么？不需要关心！！
// 网络版本的计算器，长服务
class TcpServer
{
public:
    TcpServer(uint port, ioservice_t service) :_port(port), 
                                               _service(service),
                                               _isrunning(false),
                                               _listensockptr(std::make_unique<TcpSocket>())
    {
        _listensockptr->BuildTcpSockMethod(_port); 
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client);// 1. 和client通信sockfd 2. client 网络地址 // 返回值为智能指针
            if(sock == nullptr)
            {
                continue;
            }
            LOG(LogLevel::INFO) << "accet success";

            //sock && client
            //多进程程序设计
            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL) << "fork err...";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                //child -> close the listensockfd
                _listensockptr->Close();
                if(fork() > 0)
                {
                    //operate in the grandchild proccess
                    _service(sock, client); //套接字相关的操作 + 客户端的网络地址信息
                    exit(OK);
                }
                else
                {
                    //father -- only listen
                    sock->Close();
                    pid_t rid = waitpid(id, nullptr, 0);
                    (void)rid;
                }
            }            
        }
        _isrunning = false;
    }
    ~TcpServer(){}
private:
    uint _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
    ioservice_t _service;
};